﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JeanFish.Common
{
    /// <summary>
    /// 扩展转换方法。
    /// </summary>
    public static class ConvertHelper
    {
        /// <summary>
        /// 将字符串表示的数字转换到对应进制的数字字符串。
        /// </summary>
        /// <param name="source">原数值</param>
        /// <param name="sourceBase">原数值的基</param>
        /// <param name="targetBase">目标基</param>
        /// <param name="width">转换后字符宽度</param>
        /// <param name="paddingChar">左边填充字符</param>
        /// <returns></returns>
        public static string ToTargetBase(this string source, int sourceBase, int targetBase,int? width=null,char paddingChar='0')
        {
            string target= Convert.ToString(Convert.ToInt32(source, sourceBase), targetBase);
            if(width.HasValue&&width.Value>target.Length)
                target=target.PadLeft(width.Value,paddingChar);
            return target;
        }
        /// <summary>
        /// 32位整形转到二进制，用数组表示。
        /// </summary>
        /// <param name="source">源32位整数</param>
        /// <param name="width">二进制数组长度</param>
        /// <returns></returns>
        public static int[] ToBinaryArray(this int source,int? width=null)
        {
            return source.ToString().ToTargetBase(10, 2,width).Select( _ => _ - '0').ToArray();
        }
    }
}
